 <template>
  <div>

    <Row>
      <!--左侧导航栏-->
      <i-col :span="isExpanded?5:0" class="menu_left" v-show="isExpanded && !isMobile()">
        <Tree :data="leftTreeFolders" :multiple="false" :render="renderContent" style="text-align: left"></Tree>
      </i-col>


      <!--右侧数据展示区域-->
      <i-col :span="isExpanded?19:24" :xs="{span: 24}" :sm="{span: isExpanded?19:24}" style="background: white">
        <div class="base_padding">
          <Affix >
            <div style="background-color: #fff">
            <Row>
              <!--面包屑-->
              <i-col  style="text-align: left" :xs="{span: 24}" :sm="{span: 24}">
                <Breadcrumb>
                  <BreadcrumbItem v-for="item in tStatus.breadcrumbList" >
                    <span style="cursor: pointer"  @click="selectedFolderForBar(item)"><Icon type="ios-folder-open" /> {{item.name}}</span>
                  </BreadcrumbItem>
                </Breadcrumb>
              </i-col>

              <!--功能-->
              <i-col :xs="{span: 24}" :sm="{span: 24}" style="text-align: right" v-has=tRole.IMAGE_1_100>
                <Upload :action="uploadUrl" :before-upload="beforeUpload" :data="param.uploadFolderParam" :with-credentials="false"
                        :on-success="uploadImageSuccess" :on-progress="uploadImageProgress" accept="image/png,image/jpeg,image/jpg" multiple
                        :on-error="uploadImageError" :show-upload-list="false"
                        style="display: inline-block;" v-if="!tStatus.batchDelete.isBatch">
                  <Button type="primary" icon="md-cloud-upload" class="tiy_btn"   >
                    上传图片
                  </Button>
                </Upload>
                <Button type="primary" icon="md-add" class="tiy_btn"  @click="addFolder" v-if="!tStatus.batchDelete.isBatch" >新建文件夹</Button>
                <Button type="error" icon="md-trash" class="tiy_btn" @click="batchDelete" v-if="tStatus.batchDelete.isBatch" :disabled="tStatus.modalDelete.folder.objectIds.length <= 0">删除所选</Button>
                <Button type="primary" icon="md-trash" class="tiy_btn" @click="batchDeleteImages"  >
                  {{tStatus.batchDelete.isBatch?'取消批量操作':'批量删除图片'}}
                </Button>
              </i-col>
            </Row>

              <hr>

              <Row class="y_query_right" style="width: 100%;">
                <i-col span="12" :xs="{span: 24}" :sm="{span: 12, offset: 0}">
                  <Input v-model.trim="param.folderList.keyCode" style="width: 250px;" class="modal_form_input y_condition" placeholder="请输入文件名或文件夹名" clearable
                         v-if="!tStatus.batchDelete.isBatch"/>
                  <Button type="success" icon="md-search" class="tiy_btn y_condition" @click="search" v-if="!tStatus.batchDelete.isBatch">搜索</Button>
                <Select v-model="param.folderList.orderList" @on-change="changeOrder" placeholder="请选择排序"
                        :label-in-value=true class="modal_form_input y_condition" v-if="!tStatus.batchDelete.isBatch">
                  <Option value="1" :key="1">按时间排序
                    <Icon type="md-arrow-up"></Icon>
                  </Option>
                  <Option value="2" :key="2">按时间排序
                    <Icon type="md-arrow-down"></Icon>
                  </Option>
                  <Option value="3" :key="3">按名称排序
                    <Icon type="md-arrow-up"></Icon>
                  </Option>
                  <Option value="4" :key="4">按名称排序
                    <Icon type="md-arrow-down"></Icon>
                  </Option>
                </Select>
              </i-col>
              </Row>
              <hr>
            </div>

          </Affix>



          <Row>
            <i-col span="24">
              <Row style="width: 100%;">
                <!--文件夹为空提示--->
                <Alert type="warning" v-if="folderList.length == 0"
                       style="height: 250px; width: 80%; text-align: center; margin: 0 auto; text-align: center;">
                  <h3 style="margin-top: 4rem;">该文件夹下为空的 ~ 难过(ಥ﹏ಥ)</h3>
                </Alert>

                <!---产品部分--->
                <CheckboxGroup v-model="tStatus.modalDelete.folder.objectIds" style="width: 100%; max-width: 100%;">
                  <Row type="flex">
                    <i-col :span="isExpanded?6:4" v-for="item in folderListFilter" :xs="{span: 12}" :sm="{span: isExpanded?6:4}">
                      <Card :class="cardClass()" >
                        <!--文件夹-->
                        <div class="item_folder" v-if="'' == item.suffix"  @click="selectedFolder(item)">
                          <Icon type="ios-folder-outline" size="100"/>
                          <p>{{item.name}}</p>
                        </div>
                        <!--图片类型-->
                        <div class="item_folder" v-else  @click="clickImage(item)">
                          <div class="item_img_parent">
                            <Img :src="yunPath + item.yunKey"/>
                          </div>
                          <p>{{item.name}}.{{item.suffix}}</p>
                        </div>

                        <!--删除按钮-->
                        <div class="item_select"  v-if="tStatus.batchDelete.isBatch && '' != item.suffix">
                          <Checkbox  :label="item.id"  :value="tStatus.modalDelete.folder.objectIds.indexOf(item.id)!=-1">
                            &nbsp
                          </Checkbox>
                        </div>

                      </Card>


                    </i-col>
                  </Row>
                </CheckboxGroup>
              </Row>

            </i-col>
          </Row>
        </div>

        <Page :total="page.total" :page-size="page.stepNumber" :current="page.currentPage"
              @on-change="changePage"
              @on-page-size-change="sizeChange"
              show-sizer show-elevator/>
      </i-col>

    </Row>
    <!--删除确认弹出框-->
    <Modal
      v-model="tStatus.modalDelete.isShow"
      title="确认删除"
      :loading="tStatus.modalDelete.isLoading"
      @on-ok="webDelete">
      <p>确认删除<strong> {{tStatus.modalDelete.folder.name}}?</strong></p>
    </Modal>
    <!--新店铺弹出框-->
    <Modal
      v-model="tStatus.modalFolder.isShow"
      title="新建文件夹"
      :closable="false"
      :mask-closable="false"
      :loading="tStatus.modalFolder.isLoading"
      @on-ok="webAdd">

      <Form ref="addFolder" :model="param.folder" :rules="ruleFolder"
            class="modal_add_form">
        <FormItem label="文件夹名称" prop="name">
          <Input v-model.trim="param.folder.name" placeholder="请输入"
                 class="modal_form_input"></Input>
        </FormItem>
      </Form>

    </Modal>
    <!--查看图片弹出框-->
    <Modal
      v-model="tStatus.modalImage.isShow"
      title=""
      :styles="{align:'center'}"
      :scrollable=true>
      <div slot="footer"></div>
      <div align="center"><Img :src="tStatus.modalImage.url" style="max-width: 300px"/></div>
    </Modal>
  </div>
</template>

<!--javascript 代码-->
<script>

  import ICol from "../../../node_modules/view-design/src/components/grid/col";
  import tiyData from "./js/image/image_data"
  import {init, webAdd, webDelete, webList, webFolderListByParentId} from "./js/image/image_funs"
  import {imageSizeModal} from "../js/commonUtils";
  import ApiBase from "../../api/moudles/ApiBase";

  export default {
    data(){
      return {
        tRole:{
          IMAGE_1_100:"IMAGE-1-100"
        },
        page: tiyData.tPage,
        param: tiyData.tParams,
        yunPath: this.$store.getters.imgPrefix,
        tData: tiyData.tData,
        tStatus: tiyData.tStatus,
        folderList: tiyData.tData.folderList,
        uploadUrl: this.$apiImage.getUploadToOssUrl(),
        ruleFolder: tiyData.tStatus.rules,
        displaySize:100,
        imageList: [],
        imageListLength: 0,
      }
    },
    components: {
      ICol
    },
    computed: {
      isExpanded () {
        return this.$store.state.base.isExpanded
      },
      folderListFilter(){
        var self = this;
        return  this._.filter(this.folderList,function (item) {
          return !(self._.startsWith(item.name,'product_') || self._.startsWith(item.name,'products'));
        })
      },
      leftTreeFolders(){
        let self = this;
        let folders = this._.filter(this.tData.folderTreeData,function (item) {
          return !(self._.startsWith(item.name,'product_') || self._.startsWith(item.name,'products'));
        });
        // let folders = this.tData.folderTreeData;
        return folders;
      }
    },
    methods: {
      switchExpand(){
        this.$store.commit('setUIExpanded', !this.isExpanded);
      },
      selectedFolder(folderItem){
        tiyData.tPage.currentPage = 1;
        tiyData.tParams.folderList.foderId = folderItem.id;
        tiyData.tParams.folderList.level = folderItem.level + 1;
        webFolderListByParentId(this, tiyData, folderItem);
      },
      selectedForTree(folderItem){
        tiyData.tPage.currentPage = 1;
        tiyData.tParams.folderList.foderId = folderItem.id;
        tiyData.tParams.folderList.level = folderItem.level + 1;
        webFolderListByParentId(this, tiyData, folderItem);
      },
      selectedFolderForBar(folderItem){
        tiyData.tPage.currentPage = 1;
        tiyData.tParams.folderList.foderId = folderItem.id;
        tiyData.tParams.folderList.level = folderItem.level + 1;
        webFolderListByParentId(this, tiyData, folderItem);
      },
      uploadImageSuccess(response, file, fileList){
        webFolderListByParentId(this, tiyData, null);//重新请求
        let self = this;
        if(response.success){
          response.result.forEach(function(item) {
            let name = item.yunKey.substring(item.yunKey.lastIndexOf("/")+1, item.yunKey.length);
            self.imageList.push({name: name, url: self.yunPath+item.yunKey});
          });
          if(this.imageListLength == this.imageList.length) { //全部上传完毕
            this.$Spin.hide(); //隐藏遮罩层
            imageSizeModal(this, this.imageList);
            this.imageList = []; //上传图片数组清空
            this.imageListLength = 0; //上传图片数组长度重设为0
          }
        } else {
            this.$Message.error('上传图片失败！' + response.errorMessage) ;
        }
      },
      uploadImageError(error, file, fileList){
        this.$Spin.hide();
      },
      webDelete(){
        webDelete(this, tiyData);
      },
      webAdd(){
        webAdd(this, tiyData, 'addFolder');
      },
      addFolder(){
        tiyData.tParams.folder.name = '';
        tiyData.tStatus.modalFolder.isShow = true;
      },
      deleteItem(item){
        tiyData.tStatus.modalDelete.folder.objectIds.push(item.id);
        tiyData.tStatus.modalDelete.folder.type = '' !== item.suffix ? 2 : 1;
        tiyData.tStatus.modalDelete.isShow = true;
        tiyData.tStatus.modalDelete.folder.name = item.name;
      },
      batchDeleteImages(){
        if (tiyData.tStatus.batchDelete.isBatch) {
          tiyData.tStatus.batchDelete.isBatch = false;
        } else {
          tiyData.tStatus.batchDelete.isBatch = true;
          tiyData.tStatus.modalDelete.folder.objectIds.length=0;
        }
      },
      batchDelete(){
        tiyData.tStatus.modalDelete.folder.type = 2;
        tiyData.tStatus.modalDelete.isShow = true;
        tiyData.tStatus.modalDelete.folder.name = "";
      },
      uploadImageProgress(event, file, fileList){
        this.$Spin.show();
      },
      changeOrder(){
        tiyData.tPage.currentPage = 1;
        webFolderListByParentId(this, tiyData, null);
      },
      clickImage(item){
          //删除模式下
            if(tiyData.tStatus.batchDelete.isBatch){
              if (tiyData.tStatus.modalDelete.folder.objectIds.filter(selectedItem => selectedItem === item.id).length > 0) {
                tiyData.tStatus.modalDelete.folder.objectIds.forEach(function (selectedItem,index) {
                  if(selectedItem === item.id){
                    tiyData.tStatus.modalDelete.folder.objectIds.splice(index, 1);
                  }
                });
              } else {
                tiyData.tStatus.modalDelete.folder.objectIds.push(item.id);
              }
            }else{
              tiyData.tStatus.modalImage.url = this.yunPath + item.yunKey;
              tiyData.tStatus.modalImage.isShow = true;
            }



      },
      search(){
        tiyData.tPage.currentPage = 1;
        webFolderListByParentId(this, tiyData, null);
      },
      selectDelete(item){
        // if (tiyData.tStatus.modalDelete.folder.objectIds.filter(selectedItem => selectedItem === item.id).length > 0) {
        //   tiyData.tStatus.modalDelete.folder.objectIds.forEach(function (selectedItem,index) {
        //     if(selectedItem === item.id){
        //       tiyData.tStatus.modalDelete.folder.objectIds.splice(index, 1);
        //     }
        //   });
        // } else {
        //   tiyData.tStatus.modalDelete.folder.objectIds.push(item.id);
        // }
      },
      renderContent (h, {root, node, data}) {
        return h('span', {
          style: {
            display: 'inline-block',
          }
        }, [
          h('span',
            [
              h('Icon', {
                props: {
                  type: data.expand ? 'ios-folder' : 'ios-folder-outline',
                  size: 13
                },
                style: {
                  marginRight: '8px'
                }
              }),
              h('span', data.title)
            ]),
        ]);
      },
      changePage(page){
        tiyData.tPage.currentPage = page;
        webFolderListByParentId(this, tiyData, null);
      },
      sizeChange(p){
        tiyData.tPage.stepNumber = p;
        webFolderListByParentId(this, tiyData, null);
      },
      beforeUpload(image) {
        this.imageListLength++;
        return this.setImageSizeParams(image);
      },
      setImageSizeParams(file) {
        let self = this;
        return new Promise((resolve, reject) => {
          let fileReader = new FileReader();
          fileReader.onload = e => {
            let src = e.target.result;
            const image = new Image();
            image.onload = function () {
              tiyData.tParams.uploadParam.picSizes.splice(0);
              tiyData.tParams.uploadParam.picSizes.push({width: this.width, height: this.height});
              let requestMsg = ApiBase.createRequestMsg(tiyData.tParams.uploadParam);
              tiyData.tParams.uploadFolderParam = {requestMsg: JSON.stringify(requestMsg)}
              resolve();
            };
            image.onerror = reject;
            image.src = src;
          };
          fileReader.readAsDataURL(file);
        })
      },
      cardClass() {
        if(this.$yMobile()) {
          return "item_card_mobile";
        }
        return "item_card";
      },
      isMobile() {
        return this.$yMobile();
      }
    },
    mounted(){
      init(this, tiyData);
      webFolderListByParentId(this, tiyData,null);
      this.$store.commit('setUIExpanded', true);
    }
  }
</script>

<!--css样式-->
<style scoped lang="less">
@import  (once,optional) "../css/base";



  .base_padding {
    padding: 20px;
    margin-bottom: 40px;
  }

  .modal_form_input {
    width: 200px;
    margin-right: 10px;
  }

  .modal_form_input {
    width: 200px;
    margin-right: 10px;
    text-align: left;

  }
  .btn_item{
    margin-right: 10px;
  }

  .menu_left{
    z-index: 0;
    border-right: solid #f1f1f1 1px;
    padding-right: 0.5rem;
    padding-top: 1rem;
    padding-bottom: 1rem;

  }

  .modal_add_form{
    padding-left:3rem;
    padding-top: 1rem;
  }



  .item_card{
    margin: 10px;
    text-align: center;
    /*border: solid #f1f1f1 1px;*/
    /*cursor: pointer;*/
    width: 180px;
    height: 170px;

    .item_folder{
      text-align: center;
      padding-top:0.5rem;
      display: -webkit-flex; /* Safari */
      display: flex;
      flex-direction: column;

      p{
        word-wrap:break-word;
        word-break:break-all;
        font-size: 0.75em;
        font-weight: 600;
        margin-top: 0.2rem;
      }

      .item_img_parent{
        height: 100px;
        text-align: center;
        img{
          max-height: 100px;
          max-width: 140px;
        }
      }

    }

    .item_select{
      position: absolute;
      right: 8px;
      top: 8px;
      margin: auto;
    }


  }

  .item_card_mobile{
    margin: 10px;
    text-align: center;
    /*border: solid #f1f1f1 1px;*/
    /*cursor: pointer;*/
    width: 130px;
    height: 150px;

    .item_folder{
      text-align: center;
      //padding-top:0.5rem;
      display: -webkit-flex; /* Safari */
      display: flex;
      flex-direction: column;

      p{
        word-wrap:break-word;
        word-break:break-all;
        font-size: 0.75em;
        font-weight: 600;
        margin-top: 0.2rem;
      }

      .item_img_parent{
        height: 60px;
        text-align: center;
        img{
          max-height: 60px;
          max-width: 100px;
        }
      }

    }

    .item_select{
      position: absolute;
      right: 8px;
      top: 8px;
      margin: auto;
    }
  }
</style>
